const Koa = require('koa');
const Router = require('@koa/router');
const { koaBody } = require('koa-body');
const path = require('path');
const fs = require('fs');

const app = new Koa();
const router = new Router();

const UPLOAD_DIR = path.join(__dirname, 'uploads');

// 确保上传目录存在
if (!fs.existsSync(UPLOAD_DIR)) {
  fs.mkdirSync(UPLOAD_DIR);
}

// 文件上传
router.post('/upload', koaBody({
  multipart: true,
  formidable: {
    uploadDir: UPLOAD_DIR, // 临时保存目录
    keepExtensions: true   // 保留原始扩展名
  }
}), async (ctx) => {
  const file = ctx.request.files?.file; // 上传字段名：file
  if (!file) {
    ctx.status = 400;
    ctx.body = { message: 'No file uploaded' };
    return;
  }

  const fileName = path.basename(file.path);
  const downloadUrl = `${ctx.origin}/download/${fileName}`;

  ctx.body = {
    message: 'File uploaded successfully',
    fileName,
    downloadUrl
  };
});

// 文件下载
router.get('/download/:filename', async (ctx) => {
  const fileName = ctx.params.filename;
  const filePath = path.join(UPLOAD_DIR, fileName);

  if (!fs.existsSync(filePath)) {
    ctx.status = 404;
    ctx.body = { message: 'File not found' };
    return;
  }

  ctx.set('Content-disposition', `attachment; filename=${fileName}`);
  ctx.body = fs.createReadStream(filePath);
});

app.use(router.routes()).use(router.allowedMethods());

const PORT = 3023;
app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});
